﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace z.Controllers {
	[z.Filters.InitializeSimpleMembership]
	public class ProductController : Controller {
		public ActionResult Index() {
			return View();
		}
		public ActionResult _Detail(int ID) {
			var m = App.db.Products.Where(x => x.ID == ID).Single();
			return View("_Detail", m);
		}
		[HttpGet]
		public ActionResult _Index(int ID) {
			var product = App.db.Products.Where(x => x.ID == ID).Single();
			return View(product);
		}
		public ActionResult List() {
			return View();
		}
		public ActionResult _List() {
			return View();
		}
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult Administer() {
			return View();
		}
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Add() {
			var m = new m.db.Product();
			return PartialView("_Admin", m);
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Delete(int ID) {
			var m = App.db.Products.Where(x => x.ID == ID).Single();
			foreach(var x in m.Occasion_Details.ToList()){
				App.db.Occasion_Details.Remove(x);
			}
			App.db.Products.Remove(m);
			App.db.SaveChanges();
			WebSocketController.SendMessenger("Product," + m.ID);
			return PartialView("Null");
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Edit(m.db.Product In) {
			App.resetDB();
			var isAdd = App.db.Products.Where(x => x.ID == In.ID).Count() == 0;
			var m = isAdd ? App.db.Products.Add(new m.db.Product())
				: App.db.Products.Where(x => x.ID == In.ID).Single();
			m.Name = In.Name;
			m.Price = In.Price;
			m.Detail = System.Web.HttpUtility.HtmlDecode(In.Detail);
			if (ModelState.IsValid) {
				try {
					App.db.SaveChanges();
				} catch (Exception ex) {
					return null;
				}
			}
			var file = Request.Files["file"];
			if (file != null && file.ContentType == "image/jpeg") {
				file.SaveAs(Server.MapPath("~/Content/img/p/" + m.ID + ".jpg"));
			}
			WebSocketController.SendMessenger("Product," + m.ID);
			return PartialView("_Admin", m);
		}
		[Authorize(Roles = "Mod,Admin")]
		public ActionResult _Show(int ID) {
			var m = App.db.Products.Where(x => x.ID == ID).Single();
			return PartialView("_Admin", m);
		}
	}
}
